package com.wjb.xietong.ota.tab2;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.wjb.xietong.R;
import com.wjb.xietong.control.WJBControl;
import com.wjb.xietong.datamanager.LoginUserDataManager;
import com.wjb.xietong.datamanager.WJBDataManager;
import com.wjb.xietong.ota.BaseFM;
import com.wjb.xietong.ota.task.OTATask;
import com.wjb.xietong.server.IRequestResultListener;
import com.wjb.xietong.server.project.ProjectParam;
import com.wjb.xietong.server.project.ProjectResponse;
import com.wjb.xietong.server.project.ProjectResponse.ProjectInfo;
import com.wjb.xietong.util.EnumDefine.Login_User_Info;
import com.wjb.xietong.view.PullToRefreshView;
import com.wjb.xietong.view.PullToRefreshView.OnFooterRefreshListener;
import com.wjb.xietong.view.PullToRefreshView.OnHeaderRefreshListener;

public class FMTab2 extends BaseFM implements OnHeaderRefreshListener,
		OnFooterRefreshListener {
	private final int MESSAGE_FRESH_LISTVIEW = 1;

	private List<ProjectInfo> projectList = new ArrayList<ProjectResponse.ProjectInfo>();
	private ListView mListView;
	private ListAdapter mAdapter;

	private PullToRefreshView mPullToRefreshView;
	private final int PAGE_INDEX = 1;
	private final int NUM_EVERY_PAGE = 50;
	private int mPageIndex = 1;

	private int imgResources[] = { R.drawable.ico_item1, R.drawable.ico_item2,
			R.drawable.ico_item3, R.drawable.ico_item4, R.drawable.ico_item5,
			R.drawable.ico_item6, R.drawable.ico_item7 };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		initData();
	}

	private void initData() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mPageIndex = 1;
		View view = super.onCreateView(inflater, container, savedInstanceState);
		setContentField(inflater.inflate(R.layout.fm_tab2, null));
		setTopBarAndAction(getString(R.string.STR_TAB_02), null,
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						gotoPageTask();
					}
				}, R.drawable.ico_my_project);

		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	protected void findView(View v) {
		mPullToRefreshView = (PullToRefreshView) v
				.findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this, PAGE_INDEX);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		mListView = (ListView) v.findViewById(R.id.id_listview);
		mAdapter = new ListAdapter(getActivity());
		mListView.setAdapter(mAdapter);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(getActivity(), OTATask.class);
				intent.putExtra("project_title", projectList.get(arg2)
						.getTitle());
				intent.putExtra("project_id", projectList.get(arg2)
						.getProjectId());
				startActivity(intent);
			}
		});

		requestData(true, mPageIndex, NUM_EVERY_PAGE);
	}

	private void gotoPageTask() {
		Intent intent = new Intent(getActivity(), OTATask.class);
		startActivity(intent);
	}

	Handler handler = new Handler(Looper.getMainLooper()) {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_FRESH_LISTVIEW:
				mListView.setAdapter(new ListAdapter(getActivity()));
				// mAdapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	/**
	 * 请求获取项目列表
	 */
	private void requestData(final boolean isRefresh, final int beginRow,
			final int endRow) {

		showProgressDialog();
		ProjectParam param = new ProjectParam();
		param.setCompanyId((Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.COM_ID));
		param.setPageIndex(beginRow);
		param.setPageSize(endRow);
		param.setUserId((Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.ID));
		WJBControl.requestGetProject(Calendar.getInstance().getTimeInMillis(),
				param, new IRequestResultListener() {

					@Override
					public void requestSuccess(long requestUniqueID) {
						hideProgressDialog();
						if(isRefresh){
							projectList.clear();// 清除上一次的数据
						}
						ProjectResponse projcet = WJBDataManager
								.getProjectResponseInfo();
						if(null != projcet.getProjectInfoList()){
							projectList.addAll(projcet.getProjectInfoList());
						}
						handler.sendEmptyMessage(MESSAGE_FRESH_LISTVIEW);
					}

					@Override
					public void requestFaield(long requestUniqueID,
							String errCode, String errMsg) {
						// do something
						hideProgressDialog();
					}
				});

	}

	@Override
	protected void setOnClickEvent() {
		// TODO Auto-generated method stub
		super.setOnClickEvent();
	}

	public class ListAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public ListAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return projectList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return projectList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_project_list,
						null);
				holder = new ViewHolder();
				/* 得到各个控件的对象 */
				holder.iconA = (ImageView) convertView.findViewById(R.id.img_a);
				holder.txtB1 = (TextView) convertView.findViewById(R.id.txt_b1);
				holder.txtB2 = (TextView) convertView.findViewById(R.id.txt_b2);

				convertView.setTag(holder); // 绑定ViewHolder对象
			} else {
				holder = (ViewHolder) convertView.getTag(); // 取出ViewHolder对象
			}

			holder.iconA.setImageResource(imgResources[position
					% imgResources.length]);
			holder.txtB1.setText("" + projectList.get(position).getTitle());
			holder.txtB2.setText("负责人:"
					+ projectList.get(position).getDescription());
			return convertView;
		}

		/* 存放控件 的ViewHolder */
		public final class ViewHolder {
			public ImageView iconA;
			public TextView txtB1;
			public TextView txtB2;
		}
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view, final int pageIndex) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mPullToRefreshView.onFooterRefreshComplete();
				mPageIndex = pageIndex;
				requestData(false, pageIndex, NUM_EVERY_PAGE);
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view, final int pageIndex) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				mPullToRefreshView.onHeaderRefreshComplete();
				mPageIndex = pageIndex;
				requestData(true, pageIndex, NUM_EVERY_PAGE);
			}
		}, 1000);
	}
}